
Zepto(function($) {
    $("input[type='search']").keydown(function(e) {
        if (e.keyCode === 13 && delivery_in_list_vm.search_word) {
            delivery_in_list_vm.do_search();
        }
    });

    $("input[type='search']").focusin(function(e) {
        showSearch();
    });

    $("input[type='search']").focusout(function(e) {
        hideSearch();
    });

    function showSearch() {
        toggleSearch($('.search-metal'), 'show');
    };

    function hideSearch() {
        toggleSearch($('.search-metal'), 'hide');
    };

    function toggleSearch(ele, direction, time) {

        if (!delivery_in_list_vm.search_word && direction === 'show') return;

        if (!time) time = 500;
        if (!direction) direction = 'hide';

        if (direction === 'show') {
            if (ele.css('display') == 'none') ele.css('display', 'block');
            else return;
        };

        var start = (new Date()).getTime();
        animate();

        function animate() {
            var now = (new Date()).getTime();
            var elapsed = now - start;
            var fraction = elapsed / time;

            if (fraction < 1) {
                var x = (direction === 'hide')? Math.cos(fraction * 0.5 * Math.PI) : Math.sin(fraction * 0.5 * Math.PI);
                ele.css('opacity', x);
                setTimeout(animate, Math.min(25, time - elapsed));
            } else {
                if (direction === 'hide') {
                    ele.css('display', 'none');
                };
            };
        };
    };

    function refresh_sort() {
        // @正翔 pg中文排序和前端排序返回的结果不同，暂时不对中文进行排序
        if (delivery_in_list_vm.current_items >= delivery_in_list_vm.max_items) {
            delivery_in_list_vm.moves.sort(function(left, right) {
              var res = left[delivery_in_list_vm.sort_name] >= right[delivery_in_list_vm.sort_name]
              res = delivery_in_list_vm.sort_direction === 'down'? res : !res;

              return res? 1 : -1;
            });
        } else {
            delivery_in_list_vm.current_items = 0;
            delivery_in_list_vm.moves = [];
            addItems(delivery_in_list_vm.current_page);
        };
    };

    function getStocks() {
        $.get('/weixin/delivery_in_list/get_stocks', function(data) {
            delivery_in_list_vm.stocks = JSON.parse(data);

            console.log(JSON.parse(data))
        });
    }

    function addItems(multiple) {
        multiple = multiple || 1;
        console.log(delivery_in_list_vm.current_items, delivery_in_list_vm.max_items)
        if (delivery_in_list_vm.current_items < delivery_in_list_vm.max_items) {
            $.ajax({
                url: '/weixin/delivery_in_list/get_items',
                data: {
                    'search_type': delivery_in_list_vm.search_type,
                    'search_word': delivery_in_list_vm.search_word,
                    'current_items': delivery_in_list_vm.current_items,
                    'numbers': multiple * delivery_in_list_vm.items_per_page,
                    'orderby': delivery_in_list_vm.sort_name,
                    'direction': delivery_in_list_vm.sort_direction,
                },
                type: 'get',
                success: function(e) {
                    var response = JSON.parse(e);
                    console.log(response)
                    delivery_in_list_vm.moves = delivery_in_list_vm.moves.concat(response.res);
                    delivery_in_list_vm.current_items = response.current_items;

                    delivery_in_list_vm.do_search(delivery_in_list_vm.search_type);
                },
                async: true,
            });
        };
    };

    function refresh_search_word(search_type) {
        if (search_type === 'product_name') delivery_in_list_vm.search_word_display = '产品名称';
        else if (search_type === 'picking_name') delivery_in_list_vm.search_word_display = '关联单据';
        else if (search_type === 'all') delivery_in_list_vm.search_word_display = '全部';
    }

    var delivery_in_list_vm = avalon.define({
        $id: 'delivery-in-list',
        search_word: '',
        sort_name: 'product_name',
        sort_direction: 'up',
        search_type: 'all',
        search_word_display: '全部',
        current_index: 0,  // 当前页（搜索条件后）
        current_length: 0,  // 全部数据（搜索条件后）

        stocks: [], // 全部可选值的仓库
        current_page: 1,  // 当前列表分页
        items_per_page: 15,  // 每页展示多少行数据

        current_items: 0,  // 实际数据
        max_items: $('#hidden_max_items').val(),  // 全部有效数据（包含还未取到的系统数据）
        is_warehouse_user: $('#hidden_is_warehouse_user').val() === 'True',
        moves: [],
        $computed: {
            pages: {
                get: function() {
                    return Math.ceil(this.current_length / this.items_per_page);
                }
            }
        },
        location_change: function(move_id, location) {
            var stocks = delivery_in_list_vm.stocks.filter(function(stock) { return stock.name === location });

            if (stocks.length > 0) {
                $.post('/weixin/delivery_in_list/change_location', {
                    move_id: move_id,
                    location_id: stocks[0].id
                })
            }
        },
        scanCode: function() {
            wx.scanQRCode({
                desc: 'scanQRCode desc',
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                    if (res.errMsg === 'scanQRCode:ok') {
                        $.get('/weixin/delivery_in_list/get_product_by_ean13', {ean13: res.resultStr}, function(e) {
                            var response = JSON.parse(e);
                            if (response.res === 'success') {
                                window.location = '/weixin/delivery_in?product_id=' + response.product_id;
                            } else {
                                $.alert(response.message);
                            }
                        });
                    } else {
                        $.alert('抱歉，扫码失败，请重新扫码');
                    }
                },
            });
        },
        sort: function(word) {
            if (word === delivery_in_list_vm.sort_name) {
                delivery_in_list_vm.sort_direction = delivery_in_list_vm.sort_direction === 'up'? 'down' : 'up';
            } else {
                delivery_in_list_vm.sort_direction = 'up';
            }

            delivery_in_list_vm.sort_name = word;
            refresh_sort();
            delivery_in_list_vm.do_search();
        },
        do_search: function(search_type) {  // 暂时只支持简单的名称搜索
            // var old_search_type = delivery_in_list_vm.search_type;
            if (search_type) {
                delivery_in_list_vm.search_type = search_type;
                refresh_search_word(search_type);
            };
            delivery_in_list_vm.current_index = (delivery_in_list_vm.current_page - 1) * delivery_in_list_vm.items_per_page;

            var word = delivery_in_list_vm.search_word.toLowerCase(),
                search_type = delivery_in_list_vm.search_type,
                current_page_index = 0;
                first_index = delivery_in_list_vm.items_per_page * (delivery_in_list_vm.current_page - 1),
                last_index = delivery_in_list_vm.items_per_page * delivery_in_list_vm.current_page,

            delivery_in_list_vm.moves.forEach(function(move) {
                if (current_page_index < last_index && current_page_index >= first_index) {
                    var matching = false;
                    if (word) {
                        if (search_type === 'product_name') {
                            if (move.product_name.toLowerCase().indexOf(word) != -1) matching = true;
                        } else if (search_type === 'picking_name') {
                            if (move.picking_name.toLowerCase().indexOf(word) != -1) matching = true;
                        } else if (search_type === 'all') {
                            if (move.picking_name.toLowerCase().indexOf(word) != -1 || move.product_name.toLowerCase().indexOf(word) != -1) matching = true;
                        };
                    } else matching = true;

                    if (matching) current_page_index += 1;
                    move.visible = matching;
                } else {
                    current_page_index += 1;
                    move.visible = false;
                }
            });

            $.ajax({
                url: '/weixin/delivery_in_list/get_current_length',
                data: {
                    'search_type': delivery_in_list_vm.search_type,
                    'search_word': delivery_in_list_vm.search_word,
                },
                success: function(e) {
                    var response = JSON.parse(e);
                    delivery_in_list_vm.current_length = response.current_length;

                    if (delivery_in_list_vm.pages && delivery_in_list_vm.current_page > delivery_in_list_vm.pages) {
                        delivery_in_list_vm.current_page = delivery_in_list_vm.pages;
                        delivery_in_list_vm.do_search();
                    };
                },
                async: true,
            });

            hideSearch();
            if (current_page_index < last_index) addItems();
        },
        next_page: function() {
            if (delivery_in_list_vm.current_length - delivery_in_list_vm.current_index > delivery_in_list_vm.items_per_page) {
                $('.content').scrollTop(0);
                delivery_in_list_vm.current_page = delivery_in_list_vm.current_page + 1;
                delivery_in_list_vm.do_search();
            };
        },
        previous_page: function() {
            if (delivery_in_list_vm.current_page > 1) {
                $('.content').scrollTop(0);
                delivery_in_list_vm.current_page = delivery_in_list_vm.current_page - 1;
                delivery_in_list_vm.do_search();
            };
        },
        receive_product: function(move) {
            if (!move.location) {
                $.alert('必须先选择目标库位');
                return;
            }

            $.confirm('确认收货?', function() {
                $.ajax({
                    url: '/weixin/delivery_in/action_done',
                    data: {'move_id': move.id},
                    type: 'post',
                    success: function(e) {
                        move.visible = false;
                    },
                });
            });
        },
    });

    delivery_in_list_vm.$watch('search_word', function(word) {
        if (word) {
            showSearch();
        } else {
            delivery_in_list_vm.do_search();
            hideSearch();
        }
    });

    addItems();
    getStocks();
    avalon.scan();

});
